package com.yusiji.config;

import com.alibaba.druid.pool.DruidDataSource;
import com.mchange.v2.c3p0.ComboPooledDataSource;
import com.yusiji.io.Resources;
import com.yusiji.pojo.Configuration;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.beans.PropertyVetoException;
import java.io.InputStream;
import java.util.List;
import java.util.Properties;

public class XMLConfigBuilder {

    private Configuration configuration;

    public XMLConfigBuilder(){
        this.configuration = new Configuration();
    }

    public Configuration parseConfig(InputStream in) throws DocumentException, PropertyVetoException {
        Document document = new SAXReader().read(in);
        Element rootElement = document.getRootElement();
        List<Element> list = rootElement.selectNodes("//properties");

        Properties properties = new Properties();
        for (Element element: list) {
            String name =element.attributeValue("name");
            String value =element.attributeValue("value");
            properties.setProperty(name,value);
        }

        DruidDataSource druidDataSource = new DruidDataSource();
        druidDataSource.setDriverClassName(properties.getProperty("databaseDriver"));
        druidDataSource.setUrl(properties.getProperty("databaseUrl"));
        druidDataSource.setUsername(properties.getProperty("username"));
        druidDataSource.setPassword(properties.getProperty("password"));
        configuration.setDataSource(druidDataSource);
//        ComboPooledDataSource comboPooledDataSource = new ComboPooledDataSource();
//        comboPooledDataSource.setDriverClass(properties.getProperty("databaseDriver"));
//        comboPooledDataSource.setJdbcUrl(properties.getProperty("databaseUrl"));
//        comboPooledDataSource.setUser(properties.getProperty("username"));
//        comboPooledDataSource.setPassword(properties.getProperty("password"));
//        configuration.setDataSource(comboPooledDataSource);


        List<Element> mapperList = rootElement.selectNodes("//mapper");

        for (Element element: mapperList) {
            String mapperPath = element.attributeValue("resource");
            XMLMapperConfigBuilder xmlMapperConfigBuilder = new XMLMapperConfigBuilder(configuration);
            InputStream inputStream = Resources.getResourceAsSteam(mapperPath);
            xmlMapperConfigBuilder.parseConfig(inputStream);
        }
        return configuration;

    }

}
